package com.tenglong.teacher.ui.answerq.answer;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cuotibao.zhuoxiao.basics.BaseFragment;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.cuotibao.zhuoxiao.basics.utils.recyview.DividerSpaceItemDecoration;
import com.netease.nim.uikit.business.session.constant.Extras;
import com.netease.nim.uikit.impl.customization.DefaultP2PSessionCustomization;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.AnswerInfo;
import com.tenglong.teacher.data.resultInfo.ClientUserInfo;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.WebRestApi;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.port.MainFragmentRubsh;
import com.tenglong.teacher.ui.adapter.AnswerAdapter;
import com.tenglong.teacher.ui.answerq.chat.P2PChatActivity;
import com.tenglong.teacher.ui.utils.NimUtils;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyAnswerChildFragment extends BaseFragment implements MainFragmentRubsh, AnswerAdapter.AnswerListener, OnRefreshListener {

    public static final String KEY_ANSWER_TAG = "key_answer_tag";
    private RecyclerView mRecyclerView;
    private List<AnswerInfo> infos;
    private AnswerAdapter mAdapter;
    private boolean isLoadWindow = false;
    private String tag;
    private View noData;
    private int mClickPosition = -1;
    private SmartRefreshLayout mSmartRefreshLayout;


    public MyAnswerChildFragment() {
        // Required empty public constructor
    }

    public static MyAnswerChildFragment getInstance(String tag) {
        MyAnswerChildFragment f = new MyAnswerChildFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_ANSWER_TAG, tag);
        f.setArguments(bundle);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my_answer_child, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tag = getArguments().getString(KEY_ANSWER_TAG);
        initView(view);
        initRecy();
        setAdapter();
        setLisreners();
        requestData();
        isLoadWindow = true;
    }


    private void setLisreners() {
        mAdapter.setAnswerListener(this);
        mSmartRefreshLayout.setEnableLoadMore(false);
        mSmartRefreshLayout.setOnRefreshListener(this);
    }

    private void requestData() {
        if (isFirstDownLoad && !tag.equals(MyAnswerFragment.NOT_ANSWER)) {
            showProgressDialog("数据加载中...");
            isFirstDownLoad = false;
        }
        ClientUserInfo info = DataState.getInstance().getUserInfo();
        WebRestApi service = CreateRequestEntity.getWebService();
        Call<BaseResult<List<AnswerInfo>>> call;
        switch (tag) {
            case MyAnswerFragment.NOT_ANSWER:
                call = service.getAnswerListInfo("-1", 1, "1");
                break;
            case MyAnswerFragment.ALREADY_ANSWER:
                call = service.getAnswerListInfo("-1", 1, "3");
                break;
            default:
                call = service.getCollectListInfo(info.getId(), "-1", 1);
        }
        call.enqueue(new Callback<BaseResult<List<AnswerInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<AnswerInfo>>> call, Response<BaseResult<List<AnswerInfo>>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    infos.clear();
                    infos.addAll(response.body().data);
                    mAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
                noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                mSmartRefreshLayout.finishRefresh(true);
                dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseResult<List<AnswerInfo>>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                mSmartRefreshLayout.finishRefresh(false);
                dismissProgressDialog();
            }
        });
    }

    private void initRecy() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(tag.equals(MyAnswerFragment.ALREADY_COLLECT) ? new
                DividerSpaceItemDecoration(Utils.dip2px(mContext, 15), Utils.dip2px(mContext, 15)) : new DividerSpaceItemDecoration(Utils.dip2px(mContext, 15)));
    }

    private void setAdapter() {
        infos = new ArrayList<>();
        mAdapter = new AnswerAdapter(infos, tag);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initView(View view) {
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        noData = view.findViewById(R.id.noData);
        mSmartRefreshLayout = view.findViewById(R.id.smartRefreshLayout);
        ClassicsHeader headerView = new ClassicsHeader(getContext());
        ClassicsFooter footView = new ClassicsFooter(getContext());
        headerView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        footView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        mSmartRefreshLayout.setRefreshHeader(headerView);
        mSmartRefreshLayout.setRefreshFooter(footView);
    }

    @Override
    public void refresh() {
        if (isAdded() && isLoadWindow) {
            requestData();
        }
    }

    @Override
    public void onAnswerClick(final int position) {
        if (infos == null || infos.size() == 0 || position == -1) return;
        final AnswerInfo info = infos.get(position);
        mClickPosition = position;
        Intent intent = new Intent();
        intent.setClass(mContext, P2PChatActivity.class);
        intent.putExtra(Extras.EXTRA_ACCOUNT, info.studentid);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, new DefaultP2PSessionCustomization());
        intent.putExtra(Extras.KEY_SE_ID, info.id);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(Extras.KEY_INPUT_BOX_STATE, info.statusid != 3);
        intent.putExtra(Extras.KEY_SELECT_STATE, info.collect);
        intent.putExtra(Extras.KEY_ANSWER_STATUE, info.statusid);
        intent.putExtra(Extras.EXTRA_ANCHOR, info.questioning == null ? null : NimUtils.createQuestionSessionIdUtiMesssage(info, NimUtils.ANSWER_QESTION_TYPE, info.id));
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_P2P_CHAT_ACTIVITY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_P2P_CHAT_ACTIVITY:
                    requestData();
                    break;
            }
        }
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        requestData();
    }
}
